const PENDING = 'pending'; // 等待
const FULFILLED = 'fulfilled'; // 成功
const REJECTED = 'rejected'; // 失败

class MyPromise {
  constructor (executor) {
    executor(this.resolve, this.reject)
  }
  // promise 状态
  status = PENDING;
  // 成功后的值
  value = undefined;
  // 失败后的值
  reason = undefined;

  successCallback = undefined;

  failCallback = undefined;
  resolve = (value) => {
    // 如果状态不是等待,阻止程序向下运行
    if (this.status !== PENDING) return;
    // 将状态更改为成功
    this.status = FULFILLED;
    // 保存成功之后的值
    this.value = value;
    this.successCallback && this.successCallback(this.value)
  }
  reject = (reason) => {
    // 如果状态不是等待,阻止程序向下运行
    if (this.status !== PENDING) return;
    // 将状态更改为失败
    this.status = REJECTED;
    // 保存失败后的原因
    this.reason = reason;
    this.failCallback && this.failCallback(reason)
  }
  then (successCallback, failCallback) {
    // 判断状态
    if (this.status === FULFILLED) {
      successCallback(this.value);
    } else if (this.status === REJECTED) {
      failCallback(this.reason)
    } else {
      this.successCallback = successCallback;
      this.failCallback = failCallback;
    }
  }
}

const p1 = new MyPromise((resolve, reject) => {
  setTimeout(() => {
    resolve('1')
  }, 1000)
})

p1.then((res) => {
  console.log('res', res)
})